﻿using System;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Net;
using System.Xml;
using System.Xml.Serialization;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Configuration;
using System.Reflection;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime;
using System.Runtime.InteropServices;

using PickGold.Util;

namespace PickGold.Web
{
	/// <summary>
	/// 将对象转成【Json】字符串，同时可以扩展或更改生成后的对象成员值
	/// </summary>
	[ComVisible(true)]
	[ClassInterface(ClassInterfaceType.AutoDispatch)]
	public class Json : JsonBuilder, IJson
	{
		/// <summary>
		/// 构造一Json实例
		/// </summary>
		public Json() : base() { }

		/// <summary>
		/// 构造一Json实例
		/// </summary>
		/// <param name="graph">要转换的对象</param>
		public Json(object graph) : base(graph) { }

		/// <summary/>
		public override int Render(TextWriter output, object graph, IDictionary<object, string> stack, string path, BindingFlags flags, string prefix)
		{
			var c = graph as Control;
			if (c != null)//将控件数据转成字符串。
			{
				if (!string.IsNullOrEmpty(prefix))
					output.Write(prefix);
				var json = graph as IJsonBuilder;
				if (json != null)
					return json.Render(output) + 1;

				var sb = new StringBuilder();
				var sw = new StringWriter(sb);
				var htw = new HtmlTextWriter(sw);
				c.RenderControl(htw);
				htw.Close();
				sw.Close();
				htw.Dispose();
				sw.Dispose();
				if (!string.IsNullOrEmpty(prefix))
					output.Write(prefix);
				output.Write("\"");
				output.Write(StringUtil.JsEncode(sb.ToString()));
				output.Write("\"");
				return 1;
			}

			return base.Render(output, graph, stack, path, flags, prefix);
		}

		/// <summary>
		/// 设置变量名
		/// </summary>
		/// <param name="parent">父变量名，如果为“/”则为“window”对象</param>
		/// <param name="ajax">变量名</param>
		/// <returns>变量名</returns>
		public string SetVariable(string parent, IWebPage ajax)
		{
			if (ajax.Ajax == null)
				return null;

			return WebUtil.SetVariable(this, parent, (ajax.Context.Items.Contains(WebUtil.AJAX_KEY) ? ajax.Context.Items[WebUtil.AJAX_KEY] as string : ajax.Ajax.Name) ?? ajax.Ajax.Name);
		}
		/// <summary>
		/// 设置变量名
		/// </summary>
		/// <param name="parent">父变量名，如果为“/”则为“window”对象</param>
		/// <param name="context">变量名</param>
		/// <returns>变量名</returns>
		public string SetVariable(string parent, HttpContext context)
		{
			if (context == null)
				return null;

			var variable = context.Items[WebUtil.AJAX_KEY] as string;
			if (string.IsNullOrEmpty(variable))
				return null;

			return WebUtil.SetVariable(this, parent, variable);
		}
	}
}
